package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//自定义拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {
    //目标资源方法执行前执行。 返回true：放行    返回false：不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("TokenInterceptor使用的线程名称是："+Thread.currentThread().getName());
//    if(true){
//        CurrentHolder.setUserId(10);
//        return true;
//    }

        String token = request.getHeader("token");
        try {
            // 解析token
            Claims claims = JwtUtils.parseJWT(token);

            Integer userId = claims.get("userId", Integer.class);
            System.out.println("从token中解析出的userId：" + userId);
            CurrentHolder.setUserId(userId);
        } catch (Exception e) {
            // 解析错误   响应401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
//        try {
//            JwtUtils.parseJWT(token);
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.setStatus(HttpStatus.UNAUTHORIZED.value());
//            return false;
//        }


        return true;
    }

    //目标资源方法执行后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle ... ");
    }

    //视图渲染完毕后执行，最后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion .... ");
        CurrentHolder.removeUserId();
    }
}